package cn.iocoder.yudao.module.digital.dal.redis.cardkeymanager;

import cn.hutool.core.util.ArrayUtil;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.module.digital.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.digital.enums.cardkeysecret.CardKeySourceEnum;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: li
 * Date: 2024/3/2
 */
@Repository
public class CardKeyManagerLockRedisDAO {
    private static final long PRODUCT_TIMEOUT_MILLIS = 1 * 60 * DateUtils.SECOND_MILLIS;
    private static final long ORDER_TIMEOUT_MILLIS = 1 * 60 * DateUtils.SECOND_MILLIS;

    @Resource
    private RedissonClient redissonClient;
//    @Resource
//    private ICardChannelManager cdkChannelManager;


    public <T> T lockProducts(Set<String> lockKeys, Callable<T> callable) {
        final List<RLock> locks = new ArrayList<>();
        for (String lockKey : lockKeys) {
            final RLock lock = redissonClient.getLock(lockKey);
            locks.add(lock);
        }

        final RedissonMultiLock multiLock = new RedissonMultiLock(ArrayUtil.toArray(locks, RLock.class));
        try {
            multiLock.lock(PRODUCT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            multiLock.unlock();
        }
    }

    public <T> T lockProduct(CardKeySourceEnum source, String cardKeyProductNo, Integer buyDenomination, Callable<T> callable) {
        return lockProduct(source, cardKeyProductNo, buyDenomination, PRODUCT_TIMEOUT_MILLIS, callable);
    }

    public <T> T lockProduct(CardKeySourceEnum source, String cardKeyProductNo, Integer buyDenomination, Long timeoutMillis, Callable<T> callable) {
        final String lockKey = getProductKey(source, cardKeyProductNo, buyDenomination);
        final RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            lock.unlock();
        }
    }

    public String getProductKey(CardKeySourceEnum source, String cardKeyProductNo, Integer buyDenomination) {
//        final boolean supportAggregatedOrder = cdkChannelManager.supportAggregatedOrder(source);
//        if (supportAggregatedOrder) {
//            // 支持聚合订单，上 source 级别全局锁
//            return String.format(RedisKeyConstants.CARD_KEY_PRODUCT_LOCK, "source_" + source.getValue());
//        } else {
        return String.format(RedisKeyConstants.CARD_KEY_PRODUCT_LOCK, source + "_" + cardKeyProductNo + "_" + buyDenomination);
//        }
    }

    public <T> T lockOrder(String orderNo, Callable<T> callable) {
        return lockOrder(orderNo, ORDER_TIMEOUT_MILLIS, callable);
    }

    public <T> T lockOrder(String orderNo, Long timeoutMillis, Callable<T> callable) {
        final String lockKey = formatOrderKey(orderNo);
        final RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            lock.unlock();
        }
    }


    private static String formatOrderKey(String orderNo) {
        return String.format(RedisKeyConstants.CARD_KEY_ORDER_LOCK, orderNo);
    }
}
